# 根据配置文件在前面控制器启动之后完成对交换机的基础配置
import subprocess
import logging
import sys
import os

sys.path.append("/home/p4/p4_load_balance/utils")

logger = logging.getLogger(None)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)


def program_switch_cli(sw_name, thrift_port, command_txt, log_dir):
    cli = "simple_switch_CLI"
    # get the port for this particular switch's thrift server

    logging.info("Configuring switch %s with file %s" % (sw_name, command_txt))
    with open(command_txt, "r") as fin:
        cli_outfile = "%s/%s_cli_output.log" % (log_dir, sw_name)
        with open(cli_outfile, "w") as fout:
            subprocess.Popen(
                [cli, "--thrift-port", str(thrift_port)], stdin=fin, stdout=fout
            )


def main(**opts):
    """
    读取配置文件*.txt，交换机的名称，以及对应的thrift_port从而完成对交换机的连接"""

    if "sw_name_to_thrift_port" in opts:
        from file_util import read_from_csv

        thrift_ports = read_from_csv(opts["sw_name_to_thrift_port"])
        for name, thrift_port in thrift_ports:
            program_switch_cli(
                name,
                thrift_port,
                command_txt=f"/home/p4/p4_load_balance/S_Probe/tree-topo/{name}-runtime.txt",
                log_dir="build",
            )
        # 删除csv文件
        # os.remove(opts["sw_name_to_thrift_port"])


# if __name__ == "__main__":
# main(
#     sw_name_to_thrift_port="/home/p4/p4_load_balance/S_Probe/tree-topo/sw_name_to_thrift_port.csv"
# )
